<?php
/**
 * Created by PhpStorm.
 * User: dream
 * Date: 2017/8/19
 * Time: 19:53
 */
//基础公共Controller
class MY_Controller extends CI_Controller
{
    const REQUEST_GET = "get"; //get请求
    const REQUEST_POST = "post"; //post请求

    protected $header=""; //头模板
    protected $footer=""; //脚注模板

    public function __construct()
    {
        parent::__construct();
    }

    //获取get参数
    protected function get($query_string_key,$default)
    {
        return $this->input->get($query_string_key,$default);
    }

    //获取post参数
    protected function post($query_string_key,$default)
    {

        return $this->input->post($query_string_key,$default);
    }

    //判断是否是get请求
    protected function isGet()
    {
        $req_method = strtolower($this->reqMethod());
        if($req_method==self::REQUEST_GET)
            return true;
    }

    //获取请求方法
    protected function reqMethod()
    {
        $req_method = $this->input->method();
        return $req_method;
    }

    //判断是否是post请求
    protected function isPost()
    {
        $req_method = strtolower($this->reqMethod());
        if($req_method==self::REQUEST_POST)
            return true;
    }

    //分页 bootstrap
    protected function bootstrapPagination($base_url,$count_result,$per_page,$show_count=true)
    {
        $this->load->library("BootStrap");
        return $this->bootstrap->getLinks($base_url,$count_result,$per_page,$show_count);
    }

    //加载视图
    protected  function loadView($view,$data=[])
    {
        if(!empty($this->header)){
            $this->load->view($this->header,$data);
        }
        if(!empty($view)){
            $this->load->view($view,$data);
        }
        if(!empty($this->footer)){
            $this->load->view($this->footer,$data);
        }
    }

    //获取当前时间
    protected  function getNowTime($format="Y-m-d H:i:s")
    {
        //设置时间
        date_default_timezone_set($this->config->item("time_zone_name"));
        return date($format,time());
    }

    //显示验证码
    protected function showImageCode($img_id='img',$image_ver_type="ImageVerify")
    {
        $this->load->library($image_ver_type);//采用默认thinkphp改编的验证码
        $image_ver_type::printImageCode($img_id); //类名
    }

    //检查验证码
    protected function checkImageCode($img_id='img',$image_ver_type="ImageVerify")
    {
        $this->load->library($image_ver_type);//采用默认thinkphp改编的验证码
        return $image_ver_type::checkImageCode($img_id);
    }

    //第三方发送http请求
    protected function sendHttpPost($url,$data)
    {
        $this->load->library("http/Http");
        return $this->http->post($url,$data);
    }

    //第三方发送http get请求
    protected function sendHttpGet($url,$data)
    {
        $this->load->library("http/Http");
        return $this->http->get($url,$data);
    }

    //清空本次http的会话
    protected function endHttpSession()
    {
        $this->load->library("http/Http");
        $this->http->clearCookies();
    }

    //上传文件
    protected function uploadFile($form_field_name,Array $config_file_jsons=[])
    {
        $this->load->library("upload/UploadFile",$config_file_jsons);
        $data = $this->uploadfile->uploadFile($form_field_name);
        return $data;
    }

    //制作缩略图
    protected function makeImageSmall($full_file_path,$width=75,$height=50,$image_library="gd2")
    {
        $config['image_library'] = $image_library;
        $config['source_image'] = $full_file_path;
        $config['create_thumb'] = TRUE;
        $config['maintain_ratio'] = TRUE;
        $config['width']   = $width;
        $config['height']   = $height;

        $this->load->library('image_lib', $config);
        $res = $this->image_lib->resize();
        if(!$res)
        {
            return  $this->image_lib->display_errors('<p>','</p>');
        }
        return true;
    }

    //发送短信验证码 阿里云服务
    protected function sendSms($phone_num,Array $template_vars)
    {
        $sms_config_path = $this->config->item("sms_config");
        $sms_config_json = @file_get_contents($sms_config_path);
        $sms_config_json = json_decode($sms_config_json,true);

        $this->load->library("ali-sms/AliSms",$sms_config_json);

        $validate_res = AliSms::validatePhone($phone_num);
        if(!$validate_res)
            throw new Exception("手机号码格式错误!");

        $sms_template_config_path = $this->config->item("sms_template_config");
        $send_config_json = @file_get_contents($sms_template_config_path);
        $send_config_json = json_decode($send_config_json,true);
        $res_obj = $this->alisms->sendSms($send_config_json['appSignal'],$send_config_json['sms_template_code'],$phone_num,$template_vars);

        if($sms_config_json['debug'])
        {
            return $res_obj;
        }else{
            if(strtolower($res_obj->Code)=="ok")
            {
                return true;
            }
            else{
                return false;
            }
        }
    }

    //发送邮件
    protected function sendMail($to,$subject,$body)
    {
        $this->load->library("mail/SendMail");
        return $this->sendmail->sendMail($to,$subject,$body);
    }

    //获取本次请求的ip地址  ip的物理位置信息 以及访问时间
    protected function getIPInfo()
    {
        $ip = $_SERVER["REMOTE_ADDR"];
        $ip_info = getAddressByIp($ip);
        $ip_info['ip'] = $ip;
        return $ip_info;
    }

    //控制访问时间间隔
    protected function accessTimeControl($session_name,$control_time=120)
    {
        $time_control =  $this->config->item("access_time_control");

        if(isset($time_control))
            $time_control=$time_control;
        else
            $time_control = $control_time;

        if(!session($session_name))
        {
            session($session_name,time());
        }
        else{
            $time = time()-session($session_name);
            $time_out = $time_control-$time;
            if($time<$time_control)
                throw new Exception("请稍后{$time_out}s后再试~");
            session($session_name,time());
        }
    }

    //下载文件
    protected function downLoadFile($name,$file_path)
    {
        $this->load->helper("download");
        force_download($name,$file_path);
    }

    //去除字符串所有空格 换行  变成纯文本字符串
    protected function getClearText($str)
    {
        trim($str);
        $str =str_replace("\n","",$str);
        $str =str_replace("\t","",$str);
        $str =str_replace("\r","",$str);
        $str =str_replace("\r\n","",$str);
        $str = str_replace(" ","",$str);
        $str = strip_tags($str);
        return $str;
    }

    //将字符串编码转换格式
    protected function transToUTF8($text_content,$charset=['ASCII','GB2312','GBK','UTF-8'])
    {
        //检查编码方式
        $charset = mb_detect_encoding($text_content,$charset);

        //转换为UTF-8编码格式
        if($charset&&$charset!="UTF-8")
            $text_content = iconv($charset,"UTF-8",$text_content);
        return $text_content;
    }
}